package cn.xwj.Nettytest.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * Created by thinkjoy on 2017/6/16.
 */
public class Client {
    public static String host = "127.0.0.1";
    public static int port=9527;

    public static void main(String[] args){
      EventLoopGroup worker=new NioEventLoopGroup();
      Bootstrap b=new Bootstrap();
      b.group(worker).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
          protected void initChannel(SocketChannel socketChannel) throws Exception {
//              ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
              // 以("\n")为结尾分割的 解码器
              socketChannel.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
              //定义接收类型为字符串把ByteBuf转成String
              socketChannel.pipeline().addLast("decoder",new StringDecoder());
              socketChannel.pipeline().addLast("encoder", new StringEncoder());
              socketChannel.pipeline().addLast("handler",new ClientHandler());
          }
      });
        try {
//            连接服务端
            Channel ch=b.connect(host,port).sync().channel();
//            控制台输入
            BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
            for(;;){
                String line=in.readLine();
                if(line==null) continue;
                 /*
                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
                * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
                 * */
                ch.writeAndFlush(line+"\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
